<template>
  <a-modal v-model:visible="visible" title="设备借用" :mask-closable="false" :esc-to-close="false"
    :width="width >= 500 ? 500 : '100%'" draggable @before-ok="save" @close="reset">

    <GiForm ref="formRef" v-model="form" :columns="columns" />
  </a-modal>

</template>

<script setup lang="ts">
  import { Message, type TreeNodeData } from '@arco-design/web-vue'
  import { useWindowSize } from '@vueuse/core'
  import { getUser, updateUserRole } from '@/apis/system'
  import { type ColumnItem, GiForm } from '@/components/GiForm'
  import { listUserDict } from '@/apis'

  import { useResetReactive } from '@/hooks'
  import { useDept } from '@/hooks/app'
  import { deviceLend } from '@/apis/asset/device/records'


  const emit = defineEmits < {
    (e: 'save-success'): void
  }> ()

  const { width } = useWindowSize()
  const visible = ref(false)

  const formRef = ref < InstanceType < typeof GiForm >> ()
  const [form, resetForm] = useResetReactive({})

  const { deptList, getDeptList } = useDept()

  const userList = ref < LabelValueState[] > ([]);
  // 获取用户数据
  const onSelect = async (deptId) => {
    const queryData = { status: 1, deptId: deptId }
    const { data } = await listUserDict(queryData)
    userList.value = data.map((item) => ({ ...item, value: `${item.value}` }))
  }

  const columns: ColumnItem[] = reactive([
    {
      label: '所属部门',
      field: 'deptId',
      type: 'tree-select',
      span: 24,
      required: true,
      props: {
        data: deptList,
        allowClear: true,
        allowSearch: true,
        fallbackOption: false,
        filterTreeNode(searchKey: string, nodeData: TreeNodeData) {
          if (nodeData.title) {
            return nodeData.title.toLowerCase().includes(searchKey.toLowerCase())
          }
          return false
        },
        onChange(value) {
          onSelect(value)
        },
      },
    },
    {
      label: '借用人',
      field: 'userId',
      type: 'select',
      span: 24,
      required: true,
      props: {
        options: userList,
        placeholder: "请选择用户",
        allowClear: true,
        allowSearch: true,
        allowCreate: true,
      },
    },
    {
      label: '借用日期',
      field: 'lendDate',
      type: 'date-picker',
      span: 24,
      required: true,
    },
    {
      label: '借用说明',
      field: 'lendDescription',
      type: 'textarea',
      span: 24,
      required: true,
    },
    {
      label: '计划归还日期',
      field: 'planDate',
      type: 'date-picker',
      span: 24,
      required: true,
    },
  ])

  // 重置
  const reset = () => {
    formRef.value?.formRef?.resetFields()
    resetForm()
  }

  // 保存
  const save = async () => {
    try {
      const isInvalid = await formRef.value?.formRef?.validate()
      if (isInvalid) return false
      console.log(form)
      await deviceLend(form)
      Message.success('借用成功')
      emit('save-success')
      return true
    } catch (error) {
      return false
    }

  }

  // 初始化
  const onOpen = async (deviceId) => {
    reset()
    // 指定设备id
    form.deviceId = deviceId;
    if (!deptList.value.length) {
      await getDeptList()
    }
    visible.value = true
  }

  defineExpose({ onOpen })
</script>

<style scoped lang="scss"></style>